package com.mhxy.service.impl;

import com.mhxy.constant.PicConstants;
import com.mhxy.entity.FindPicResult;
import com.mhxy.enums.Coord;
import com.mhxy.service.AbstractTask;
import com.mhxy.util.FuzzyPicUtil;
import com.mhxy.util.MouseUtil;
import com.mhxy.util.ThreadUtil;
import com.sun.jna.platform.win32.WinDef;
import lombok.extern.slf4j.Slf4j;

/**
 * 物品卖银币任务
 */
@Slf4j
public class SellSilverCoinTaskImpl extends AbstractTask {

    public SellSilverCoinTaskImpl(WinDef.HWND hwnd_0) {
        super(hwnd_0);
    }

    @Override
    public String getTaskName() throws Exception {
        return "物品卖银币";
    }

    @Override
    public Boolean before() throws Exception {
        clickEsc1();
        if (FuzzyPicUtil.findPic(hwnd_0, PicConstants.公共_商城, 2).isFinded()) {
            return true;
        }
        return goToJianYe();
    }

    @Override
    public Boolean execute() throws Exception {
        // 查找并点击商城
        if (!FuzzyPicUtil.findAndClickRandom(hwnd_0, hwnd_0, PicConstants.公共_商城)) {
            return false;
        }
        ThreadUtil.sleep1();

        if (!FuzzyPicUtil.findPic(hwnd_0, PicConstants.物品卖银币任务_商会已选择,3,0.95).isFinded()) {
            if (!FuzzyPicUtil.findAndClickRandom(hwnd_0, hwnd_0, PicConstants.物品卖银币任务_商会未选择)) {
                log.error("【物品卖银币任务】商会图标未找到！退出任务");
                return false;
            }
        }

        // 点击出售物品
        if (!FuzzyPicUtil.findAndClickRandom(hwnd_0, hwnd_0, PicConstants.物品卖银币任务_我要出售)) {
            return false;
        }

        // 选择出售第一个物品
        MouseUtil.lClickRandom(hwnd_0, Coord.SELL_FIRST_XY.getX(), Coord.SELL_FIRST_XY.getY());
        MouseUtil.lClickRandom(hwnd_0, Coord.SELL_FIRST_XY.getX(), Coord.SELL_FIRST_XY.getY());

        return true;
    }

    @Override
    public Boolean after() throws Exception {
        pic = FuzzyPicUtil.findPic(hwnd_0, PicConstants.物品卖银币任务_出售,3);
        if (!pic.isFinded()) {
            log.error("【{}】没有找到“出售”按钮", getTaskName());
        }
        // 循环点击出售，直到完成
        for (int i = 1; i < 50; i++) {
            log.info("【{}】售卖第{}次", getTaskName(), i);
            MouseUtil.lClickRandom(hwnd_0, pic.getPicX(), pic.getPicY());
            MouseUtil.lClickRandom(hwnd_0, pic.getPicX(), pic.getPicY());
            MouseUtil.lClickRandom(hwnd_0, pic.getPicX(), pic.getPicY());
            // 没有可以出售的商品
            if (FuzzyPicUtil.findPic(hwnd_0, PicConstants.物品卖银币任务_出售完成,1).isFinded()) {
                log.info("【{}】没有可以出售的商品，任务已完成，退出！", getTaskName());
                clickEsc1();
                return true;
            }
        }
        return true;
    }
}
